import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import { getApiConfig, API_ENDPOINTS } from '../config/api'

const API_BASE_URL = getApiConfig().baseURL

export const useChatStore = defineStore('chat', () => {
  // 状态
  const sessions = ref([])
  const currentSession = ref(null)
  const conversations = ref([])
  const loading = ref(false)
  const error = ref(null)

  // 计算属性
  const currentSessionId = computed(() => currentSession.value?.session_id)

  // 获取会话列表
  const fetchSessions = async () => {
    try {
      loading.value = true
      const response = await axios.get(`${API_BASE_URL}${API_ENDPOINTS.sessions}`)
      if (response.data.code === 200) {
        sessions.value = response.data.data.sessions
      }
    } catch (err) {
      error.value = '获取会话列表失败'
      console.error('获取会话列表失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 创建新会话
  const createSession = async () => {
    try {
      loading.value = true
      const response = await axios.post(`${API_BASE_URL}${API_ENDPOINTS.sessions}`)
      if (response.data.code === 200) {
        const newSession = response.data.data
        sessions.value.unshift(newSession)
        currentSession.value = newSession
        conversations.value = []
        return newSession
      }
    } catch (err) {
      error.value = '创建会话失败'
      console.error('创建会话失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 发送消息
  const sendMessage = async (message) => {
    if (!currentSession.value) {
      await createSession()
    }

    try {
      loading.value = true
      const response = await axios.post(`${API_BASE_URL}${API_ENDPOINTS.chat}`, {
        user_input: message,
        session_id: currentSession.value.session_id
      })

      if (response.data.code === 200) {
        const conversation = {
          id: Date.now(),
          user_input: message,
          ai_response: response.data.data.response,
          timestamp: new Date().toISOString()
        }
        conversations.value.push(conversation)
        return conversation
      }
    } catch (err) {
      error.value = '发送消息失败'
      console.error('发送消息失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取对话历史
  const fetchConversations = async (sessionId) => {
    try {
      loading.value = true
      const response = await axios.get(`${API_BASE_URL}${API_ENDPOINTS.sessionConversations(sessionId)}`)
      if (response.data.code === 200) {
        conversations.value = response.data.data.conversations.map(conv => ({
          id: conv.conversation_id,
          user_input: conv.user_input,
          ai_response: conv.final_response,
          timestamp: conv.created_at
        }))
      }
    } catch (err) {
      error.value = '获取对话历史失败'
      console.error('获取对话历史失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 选择会话
  const selectSession = async (session) => {
    currentSession.value = session
    await fetchConversations(session.session_id)
  }

  // 删除会话
  const deleteSession = async (sessionId) => {
    try {
      const response = await axios.delete(`${API_BASE_URL}${API_ENDPOINTS.sessionDetail(sessionId)}`)
      if (response.data.code === 200) {
        sessions.value = sessions.value.filter(s => s.session_id !== sessionId)
        if (currentSession.value?.session_id === sessionId) {
          currentSession.value = null
          conversations.value = []
        }
      }
    } catch (err) {
      error.value = '删除会话失败'
      console.error('删除会话失败:', err)
    }
  }

  // 清空记忆
  const clearMemory = () => {
    conversations.value = []
    error.value = null
  }

  return {
    // 状态
    sessions,
    currentSession,
    conversations,
    loading,
    error,
    
    // 计算属性
    currentSessionId,
    
    // 方法
    fetchSessions,
    createSession,
    sendMessage,
    fetchConversations,
    selectSession,
    deleteSession,
    clearMemory
  }
}) 